<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */
 
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\model\Order as OrderModel;
use app\admin\validate\OrderValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use think\facade\Filesystem;
class Order extends BaseController

{
	/**
     * 构造函数
     */
	protected $uid;
	protected $model;
    public function __construct()
    {
        $this->model = new OrderModel();
		$this->uid = get_login_admin('id');
    }
    /**
    * 数据列表
    */
    public function datalist()
    {
        if (request()->isAjax()) {
			$param = get_params();
			$where = [];
            if(!empty($param['name'])){
                $where[] = ['o.name', 'like', '%' . $param['name'] . '%'];
            }
            if(!empty($param['region'])){
                $where[] = ['o.region', '=', $param['region'] ];
            }
            if(!empty($param['order_no'])){
                $where[] = ['o.order_no', '=', $param['order_no'] ];
            }
            if(!empty($param['sorting_admin'])){
                $where[] = ['o.sorting_admin|o.sorting_admin2', '=', $param['sorting_admin'] ];
            }
			if(!empty($param['delivery_time1'])){
                $where[] = ['o.delivery_time', '>=', strtotime($param['delivery_time1'])];
            }
            if(!empty($param['delivery_time2'])){
                $where[] = ['o.delivery_time', '<=', strtotime($param['delivery_time2'])];
            }
            
            $list = $this->model->getOrderList($where,$param);
            //pr($list);
            $sunhao=0;
            $chuku=0;
            $ruku=0;
            $sorting=0;
            foreach($list as $key=>$val){
                foreach ($val as $k => $v) {
                    if ($v === null) {
                        $val[$k] = '';
                    }
                }
                $list[$key]['produced_time']=$val['produced_time']? date('Y-m-d',$val['produced_time']) : '';
                $list[$key]['delivery_time']=$val['delivery_time']? date('Y-m-d',$val['delivery_time']) : '';
                if($val['out_storage']>0 && $val['in_storage']>0 && $val['sorting']>0){
                    $chuku= $chuku+$val['out_storage'];
                    $ruku= $ruku+$val['in_storage'];
                    $sorting= $sorting+$val['sorting'];
                }
                
                $list[$key]['goods'] = Db::name('order')->where('o.order_no', $val['order_no'])
                    ->field('o.*,p.name as purchaser,p.phone,p.address,p.user,n.nianji,a.username,f1.name as fenjian1,f2.name as fenjian2')
                    ->alias('o')
                    ->leftJoin('purchaser p', 'o.purchaser = p.id')
                    ->leftJoin('nianji n', 'o.region = n.id')
                    ->leftJoin('admin a', 'o.create_admin = a.id')
                    ->leftJoin('fenjian f1', 'o.sorting_admin = f1.id')
                    ->leftJoin('fenjian f2', 'o.sorting_admin2 = f2.id')
                    ->select();
                
            }
            $sunhao= $chuku-$ruku-$sorting;
            if($this->uid==1){
                $msg='当前损耗为：'.$sunhao.'， 出库数为：'.$chuku.'，  入库数为：'.$ruku.'，  分拣量为：'.$sorting;
            }else{
                $msg='';
            }
            
            return table_assign(0, $msg, $list);
        }
        else{
            return view();
        }
    }

    /**
    * 添加
    */
    public function add()
    {
        if (request()->isAjax()) {		
			$param = get_params();	
			
            // 检验完整性
            try {
                validate(OrderValidate::class)->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }
			$param['create_admin'] =$this->uid;
            if(isset($param["produced_time"])){
                $param["produced_time"]= $param["produced_time"]?strtotime($param["produced_time"]):0;
            }
            if(isset($param["delivery_time"])){
                $param["delivery_time"]= $param["delivery_time"]?strtotime($param["delivery_time"]):0;
            }
            $this->model->addOrder($param);
        }else{
			return view();
		}
    }
	

    /**
    * 编辑
    */
    public function edit()
    {
		$param = get_params();
		
        if (request()->isAjax()) {
            //pr($param);			
            // 检验完整性
            try {
                validate(OrderValidate::class)->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }
            $param['create_admin'] =$this->uid;
			if(isset($param["produced_time"])){
                $param["produced_time"]= $param["produced_time"]?strtotime($param["produced_time"]):null;
            }
            if(isset($param["delivery_time"])){
                $param["delivery_time"]= $param["delivery_time"]?strtotime($param["delivery_time"]):null;
            }
            $this->model->editOrder($param);
        }else{
			$id = isset($param['id']) ? $param['id'] : 0;
            //$order_no = isset($param['order_no']) ? $param['order_no'] : 0;
			$detail = $this->model->getOrderById($id);
			if (!empty($detail)) {
                $where['order_no']= $detail['order_no'];
                $res = Db::name('order')->where($where)->select();
                //pr($res);
				View::assign('detail', $detail);
                View::assign('detail_list', $res);
				return view();
			}
			else{
				throw new \think\exception\HttpException(404, '找不到页面');
			}			
		}
    }
    public function edit_fenjian()
    {
        $param = get_params();
        
        if (request()->isAjax()) {
            /*Array
                (
                    [sorting_admin] => 1
                    [sorting_admin2] => 1
                    [order_nos] => 8202503160066,8202503160178
                )*/
            $updateData = [
            'sorting_admin'  => intval($param['sorting_admin']),
            'sorting_admin2' => intval($param['sorting_admin2']),
            ];
            $order_arr=explode(',',$param['order_nos']);
            Db::name('order')->where('order_no', 'in', $order_arr)->update($updateData);
            return to_assign();
        }else{
            $order_nos = isset($param['order_no']) ? $param['order_no'] : 0;
            View::assign('order_nos', $order_nos);
            return view();
                   
        }
    }

    /**
    * 查看信息
    */
    public function read()
    {
        $param = get_params();
		$id = isset($param['id']) ? $param['id'] : 0;
		$detail = $this->model->getOrderById($id);
		if (!empty($detail)) {
			View::assign('detail', $detail);
			return view();
		}
		else{
			throw new \think\exception\HttpException(404, '找不到页面');
		}
    }

    /**
    * 删除
	* type=0,逻辑删除，默认
	* type=1,物理删除
    */
    public function del()
    {
        $param = get_params();
		$id = isset($param['id']) ? $param['id'] : 0;
		//$type = isset($param['type']) ? $param['type'] : 0;
        $type = 1;

        $this->model->delOrderById($id,$type);
   }
   public function order_import(){

        
            return view();
        
   }
   public function upload()
    {

        $param = get_params();

        $sourse = 'file';
        if($param['region']<=0){
            return to_assign(1, '请选择县区');
        }
        if($sourse == 'file'){
            if(request()->file('file')){
                $file = request()->file('file');
            }
            else{
                return to_assign(1, '没有选择上传文件');
            }
        }
        else{
            if (request()->file('editormd-image-file')) {
                $file = request()->file('editormd-image-file');
            } else {
                return to_assign(1, '没有选择上传文件');
            }
        }

        // 获取上传文件的hash散列值
        $sha1 = $file->hash('sha1');
        $md5 = $file->hash('md5');
        $rule = [
            'image' => 'jpg,png,jpeg,gif',
            'doc' => 'doc,docx,ppt,pptx,xls,xlsx,pdf',
            'file' => 'zip,gz,7z,rar,tar',
            'video' => 'mpg,mp4,mpeg,avi,wmv,mov,flv,m4v',
        ];
        $fileExt = $rule['image'] . ',' . $rule['doc'] . ',' . $rule['file'] . ',' . $rule['video'];
        //1M=1024*1024=1048576字节
        $fileSize = 100 * 1024 * 1024;
        if (isset($param['type']) && $param['type']) {
            $fileExt = $rule[$param['type']];
        }
        if (isset($param['size']) && $param['size']) {
            $fileSize = $param['size'];
        }

        $validate = \think\facade\Validate::rule([
            'image' => 'require|fileSize:' . $fileSize . '|fileExt:' . $fileExt,
        ]);
        $file_check['image'] = $file;
        if (!$validate->check($file_check)) {
            return to_assign(1, $validate->getError());
        }
        // 日期前綴
        $dataPath = date('Ym');
        $use = 'thumb';
        $filename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file, function () use ($md5) {
            return $md5;
        });
        //$filename='202503/e3152b052b0a5449f895fb57bad03727.xlsx';$param['region']=1;

        $fullPath = Filesystem::disk('public')->path($filename);
        $spreadsheet = IOFactory::load($fullPath);
        $sheet = $spreadsheet->getActiveSheet();
        $highestRow = $sheet->getHighestRow();
        $data = [];
        if($param['region']==1){
            //河东
            $orderNo = $deliveryTime = $purchaserInfo = '';
            // 该地区Excel格式特殊，需要解析表头信息
            $orderData = [];
            $purchaserInfo = '';

            // 循环读取每一行，动态定位关键信息
            foreach ($sheet->getRowIterator() as $row) {
                $rowIndex = $row->getRowIndex();
                $cellA = $sheet->getCell('A' . $rowIndex)->getValue();
                $cellG = $sheet->getCell('G' . $rowIndex)->getValue();
                //pr($cellG);
                // 1. 提取订单号 (格式：订单号：5815216451341395)
                
                if (is_string($cellG)  && strpos($cellG, '订单号：') !== false) {
                    $orderNo = trim(str_replace('订单号：', '', $cellG));
                }
                // 2. 提取发货时间 (格式：2025-03-22 6:00 ~ 16:00发货)
                if (is_string($cellA)  &&  strpos($cellA, '发货') !== false) {
                    preg_match('/\d{4}-\d{2}-\d{2}/', $cellA, $matches);
                    $deliveryTime = strtotime($matches[0]);
                }
                // 3. 提取采购商 (格式：采购单位/联系电话：临沂二十四中学北校区/19963976978)
                if (is_string($cellA)  && strpos($cellA, '采购单位/联系电话：') !== false) {
                    $purchaserInfo = str_replace('采购单位/联系电话：', '', $cellA);
                    list($purchaserName, $purchaserPhone) = explode('/', $purchaserInfo, 2);
                }

                // 4. 定位数据行起始位置（当A列出现"序号"时，下方为数据行）
                if ($cellA == '序号') {
                    $dataStartRow = $rowIndex + 1; // 数据从下一行开始
                    break; // 结束表头解析
                }
            }
            //pr($orderNo);
            // 5. 循环读取数据行（直到出现"合计："）
            $dataStartRow=3;
            for ($row = $dataStartRow; $row <= $highestRow; $row++) {
                $cellA = $sheet->getCell('A' . $row)->getValue();
                $orderNo = $sheet->getCell('B' . $row)->getValue();
                $deliveryTime = strtotime($sheet->getCell('C' . $row)->getValue());
                $purchaserName = $sheet->getCell('H' . $row)->getValue();
                $address = $sheet->getCell('J' . $row)->getValue();
                // 遇到"合计："行结束循环
                if (strpos($cellA, '合计：') !== false) break;

                // 6. 检查采购商是否存在（不存在则自动创建）
                $purchaserExist = Db::name('purchaser')
                    ->where('name', trim($purchaserName))
                    ->where('address', trim($address))
                    ->find();
                
                if (!$purchaserExist) {
                    $purchaserData = [
                        'name'  => trim($purchaserName),
                        'address' => trim($address)
                    ];
                    $purchaserId = Db::name('purchaser')->insertGetId($purchaserData);
                } else {
                    $purchaserId = $purchaserExist['id'];
                }
                // 查重逻辑
                $currentOrderNo = $orderNo;
                $currentProductName = $sheet->getCell('D' . $row)->getValue();
                $exist = Db::name('order')
                    ->where('order_no', $currentOrderNo)
                    ->where('name', $currentProductName)
                    ->find();
                // 7. 构建数据记录
                if (!$exist) {
                    $data[] = [
                        'region'        => $param['region'],
                        'delivery_time' => $deliveryTime,
                        'order_no'      => $orderNo, // 整个表格共用同一个订单号
                        'purchaser'     => $purchaserId,
                        'name'          => $sheet->getCell('D' . $row)->getValue(), // 商品名称
                        'specification' => $sheet->getCell('D' . $row)->getValue(), // 规格
                        'sorting'       => $sheet->getCell('K' . $row)->getValue(), // 商品名称
                        'price'         => $sheet->getCell('L' . $row)->getValue(), // 单价
                        //'remark'        => '数量：' . $sheet->getCell('G' . $row)->getValue(), // 数量存入备注
                        'remark'        => $sheet->getCell('N' . $row)->getValue(), // 数量存入备注
                        'create_time'   => time(),
                        'create_admin'  => $this->uid
                    ];
                }
            }
            //pr($data);
            //pr($data);
            Db::name('order')->insertAll($data);
            $res['count']=count($data);
            // 删除临时文件
            unlink($fullPath);
            return to_assign(0, '导入成功', $res);
            exit;
        }elseif($param['region']==2){
            //沂河新区
            $data = [];
            $dataStartRow = 0;

            // 动态定位数据起始行（查找包含"学校"的标题行）
            foreach ($sheet->getRowIterator() as $row) {
                $rowIndex = $row->getRowIndex();
                if ($sheet->getCell('B'.$rowIndex)->getValue() == '学校') { // 学校列改为B列
                    $dataStartRow = $rowIndex + 1;
                    break;
                }
            }
            if ($dataStartRow < 1) {
                unlink($fullPath);
                return to_assign(1, '文件格式异常，未找到数据起始位置');
            }

            // 循环处理数据行
            for ($row = $dataStartRow; $row <= $highestRow; $row++) {
                // 终止条件检测
                $cellA = $sheet->getCell('A'.$row)->getValue();
                if (strpos($cellA, '合计：') !== false) break;

                // 基础数据提取
                $orderNo        = trim($sheet->getCell('A'.$row)->getValue()); // 订单编号
                $purchaserName  = trim($sheet->getCell('B'.$row)->getValue()); // 学校列
                $orderDate      = $sheet->getCell('C'.$row)->getValue();      // 订单日期
                $productName    = trim($sheet->getCell('F'.$row)->getValue());// 商品名称
                $unit           = $sheet->getCell('G'.$row)->getValue();      // 单位
                $price          = $sheet->getCell('H'.$row)->getValue();      // 单价
                $quantity       = $sheet->getCell('I'.$row)->getValue();      // 数量
                $remark1        = $sheet->getCell('E'.$row)->getValue();      // 订单备注
                $remark2        = $sheet->getCell('K'.$row)->getValue();      // 商品备注

                // 合并备注
                $remark = $remark1.$remark2;
                // 生成组合字段
                $deliveryTime = strtotime($orderDate);
                // 采购商处理
                $purchaserExist = Db::name('purchaser')
                    ->where('name', $purchaserName)
                    ->find();
                if (!$purchaserExist) {
                    $purchaserId = Db::name('purchaser')->insertGetId([
                        'name'    => $purchaserName
                        
                    ]);
                } else {
                    $purchaserId = $purchaserExist['id'];
                }
                // 重复数据检查（使用订单编号+商品名称）
                $exist = Db::name('order')
                    ->where('order_no', $orderNo)
                    ->where('name', $productName)
                    ->find();

                if (!$exist) {
                    $data[] = [
                        'region'         => $param['region'],
                        'delivery_time'  => $deliveryTime,
                        'order_no'       => $orderNo, // 直接使用原始订单编号
                        'purchaser'      => $purchaserId,
                        'name'           => $productName,
                        'specification'  => $productName,
                        'sorting'        => $quantity,
                        'price'          => $price,
                        'remark'         => $remark, // 合并数量与双备注
                        'create_time'   => time(),
                        'create_admin'  => $this->uid
                    ];
                }
            }
            //pr($data);
            if (!empty($data)) {
                Db::name('order')->insertAll($data);
            }
            
            //Db::name('order')->insertAll($data);
            $res['count']=count($data);
            // 删除临时文件
            unlink($fullPath);
            return to_assign(0, '导入成功', $res);
            exit;
        }else{

            for ($row = 2; $row <= $highestRow; $row++) { // 跳过表头
                /*var_dump($sheet->getCell('A' . $row)->getValue());
                pr($highestRow);*/
                //查找重复订单号
                $order_no = (string)$sheet->getCell('B' . $row)->getValue();

                //$order_num = Db::name('order')->field('id')->where('order_no', $order_no)->find();

                /*if($order_num){
                    unlink($fullPath);
                    return to_assign(1, '订单号：'.$order_no.'已存在');
                    break;
                }*/
                //查询采购商是否存在
                $purchaser = (string)$sheet->getCell('D' . $row)->getValue();
                $purchaser_num = Db::name('purchaser')->where('name', $purchaser)->find();
                //pr($purchaser_num);
                if(!$purchaser_num){
                    /*return to_assign(1, $purchaser.'此采购商不存在，请前往采购商管理进行添加！');
                    unlink($fullPath);
                    break;*/
                    $purchaserData['name'] = $purchaser;
                    $purchaserId = Db::name('purchaser')->insertGetId($purchaserData);
                    
                }else {
                    $purchaserId = $purchaser_num['id'];
                }
                
                $deliveryTime = strtotime((string)$sheet->getCell('A' . $row)->getValue());

                $currentOrderNo = $order_no;
                $currentProductName = (string)$sheet->getCell('J' . $row)->getValue();
                $exist = Db::name('order')
                    ->where('order_no', $currentOrderNo)
                    ->where('name', $currentProductName)
                    ->find();
                if (!$exist) {
                    $data[] = [
                        'region'        => $param['region'],
                        'delivery_time' => $deliveryTime,
                        'order_no'      => $order_no,
                        'status'        => (string)$sheet->getCell('C' . $row)->getValue(),
                        'purchaser'     => $purchaserId,
                        'name'          => (string)$sheet->getCell('J' . $row)->getValue(),
                        'specification' => (string)$sheet->getCell('J' . $row)->getValue(),
                        'sorting'       => (string)$sheet->getCell('N' . $row)->getValue(),
                        'remark'        => (string)$sheet->getCell('V' . $row)->getValue(),
                        'price'         => (string)$sheet->getCell('M' . $row)->getValue(),
                        'create_time'    => time(),
                        'create_admin'   => $this->uid
                        
                    ];
                }
            }
        }
        
        
        //pr($data);
        Db::name('order')->insertAll($data);
        $res['count']=count($data);
        // 删除临时文件
        unlink($fullPath);
        return to_assign(0, '导入成功', $res);
        exit;
        
    }
    
}
